package com.bvbot.core.extractor;

import static com.bvbot.core.Logger.log;

public class KitcoExtractor {

	public static final String KITCO_URL = "http://www.kitco.com/";

	public static final String GOLD_PRICE_BEFORE_TOKEN = "<td nowrap=\"nowrap\">";

	public Float extract() {
		Float result = null;
		UrlTool ex = new UrlTool();
		String kitcoHtml = ex.getHtml(KITCO_URL);
		if (kitcoHtml != null) {
			String priceString = null;
			int index = kitcoHtml.indexOf(GOLD_PRICE_BEFORE_TOKEN);
			if (index > 0) {
				int indexFirstDot = kitcoHtml.indexOf(".", index
						+ GOLD_PRICE_BEFORE_TOKEN.length());
				if (indexFirstDot > 0) {
					priceString = kitcoHtml.substring(index
							+ GOLD_PRICE_BEFORE_TOKEN.length(),
							indexFirstDot + 3);
					try {
						result = Float.valueOf(priceString);
					} catch (NumberFormatException e) {
						log("Impossible to parse string from " + priceString
								+ " : " + e.getMessage(), e);
					}
				}
			}
			if (priceString == null) {
				log("Impossible to get price from " + kitcoHtml);
			}
		} else {
			log("Impossible to get html from " + KITCO_URL);
		}
		return result;
	}

	public static void main(String[] args) {
		KitcoExtractor e = new KitcoExtractor();
		Float price = e.extract();
		if (price != null) {
			log("Current kitco price is " + price);
		} else {
			log("Impossible to extract current Kitco price");
		}
	}

}
